package com.money.mvp_dagger_simple.http;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.money.mvp_dagger_simple.http.listener.MRequestListener;
import com.money.mvp_dagger_simple.http.manager.RxApiManager;
import com.money.mvp_dagger_simple.http.response.MResponse;
import com.money.mvp_dagger_simple.http.response.MResponseCode;
import com.money.mvp_dagger_simple.http.service.ApiService;

import java.util.Map;

import retrofit2.Retrofit;
import rx.Observable;
import rx.Subscriber;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by Money on 2017/8/25.
 */


public class HttpUtil {

    private Retrofit retrofit;
    private ApiService apiService;

    public HttpUtil(Retrofit retrofit, ApiService apiService) {
        this.retrofit = retrofit;
        this.apiService = apiService;
    }

    public void post(final MRequestListener listener, final String url, Map<String, Object> map, final String reqTag, final String...byValue){

        GsonBuilder gsonBuilder = new GsonBuilder();
        final Gson gson = gsonBuilder.create();

        Observable<MResponse> observable = apiService.post(url, gson.toJson(map));

        Subscription subscription = observable.subscribeOn(Schedulers.io()).unsubscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<MResponse>() {

                    @Override
                    public void onStart() {
                        super.onStart();
                    }

                    @Override
                    public void onCompleted() { }

                    @Override
                    public void onError(Throwable e) {
                        listener.onError(url, "", reqTag, byValue);
                    }

                    @Override
                    public void onNext(MResponse mResponse) {
                        if (mResponse.getResultCode() != null){
                            switch (mResponse.getResultCode()){

                                case MResponseCode.RESULT_ERROR_CODE:
                                    listener.onError(url, mResponse.getResultDesc(), reqTag, byValue);
                                    break;
                                case MResponseCode.RESULT_SUCCESS_CODE:
                                    listener.onSuccess(url, gson.toJson(mResponse.getData()), reqTag, byValue);
                                    break;
                            }
                        }else{
                            listener.onError(url, "gson 解析异常", reqTag,byValue);
                        }
                    }
                });

        RxApiManager.getINSTANCE().add(reqTag, subscription);

    }

}
